package com.chenhs.oop.study.集合;

import java.util.ArrayList;
import java.util.Iterator;


/**
 * @program: JAVA300
 * @description: 集合的遍历的4种方式
 * @author: peanut
 * @create: 2019-02-21 22:31
 */
public class 集合的4种遍历方式 {


    public static void main(String[] args) {
        toArrayList();
    }


    public static ArrayList<String> getList() {
        ArrayList<String> list = new ArrayList();
        list.add("一");
        list.add("二");
        list.add("三");
        list.add("四");
        return list;
    }

    /* 通过foreach遍历集合*/
    public static void foreachList() {
        ArrayList<String> list = getList();
        for (String s : list) {
            System.out.println(s);
        }
    }

    /*通过普通for循环遍历*/
    public static void forList() {
        ArrayList<String> list = getList();
        for (int i = 0; i <= list.size(); i++) {

            System.out.println(list.get(i));
        }
    }

    /*  使用迭代器便利集合*/
    public static void iteratorList() {
        ArrayList<String> list = getList();
        Iterator<String> iterator = list.iterator();
        /*如果还有值*/
        while (iterator.hasNext()) {
            /**取出当前位置的值*/
            String next = iterator.next();
            System.out.println(next);

        }
    }

    /*转换为数组再遍历*/
    public static void toArrayList() {
        ArrayList<String> list = getList();
        Object[] array1 = list.toArray();
        for (Object s: array1) {
            System.out.println(s.toString());
        }

    }

}
